package com.lagou.handler;

import com.lagou.entity.RpcRequest;
import com.lagou.service.UserServiceImpl;
import io.netty.channel.*;
import io.netty.util.concurrent.EventExecutorGroup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 自定义的业务处理器
 */
@Component
@ChannelHandler.Sharable
public class UserServiceHandler extends ChannelInboundHandlerAdapter {

    @Autowired
    ApplicationContext context;

    //当客户端读取数据时,该方法会被调用
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        //注意:  客户端将来发送请求的时候会传递一个参数:  UserService#sayHello#are you ok
         //1.判断当前的请求是否符合规则
        RpcRequest request = (RpcRequest) msg;
        System.out.println("request:  "+request);

        //UserServiceImpl service = new UserServiceImpl();
        //String result = service.sayHello(msg.toString().substring(msg.toString().lastIndexOf("#")+1));
        Class<?> classInfo = Class.forName(request.getClassName());
        Object service = context.getBean(classInfo);
        String methodName = request.getMethodName();
        Method method = classInfo.getMethod(methodName);
        Object result = method.invoke(service,request.getParameters());

        //3.把调用实现类的方法获得的结果写到客户端
        ChannelFuture f = ctx.writeAndFlush(result);
        //因为异步操作，需要监听确实写出发送给客户端后才执行关闭操作
        //f.addListener(ChannelFutureListener.CLOSE);
    }

    /**
     * 进行异常处置
     * @param ctx
     * @param cause
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}
